package models

import (
	"strconv"

	"github.com/astaxie/beego/orm"
)

//GetAPIURLListByToken 根据token和访问的api来判断用户是否有权限访问
func GetAPIURLListByToken(token string, apiPath string) bool {
	// 现在先全部能访问。
	for _, apiuserurl := range apiUserUrlList {

		if apiuserurl.Enable == 1 && apiuserurl.UserToken == token && apiuserurl.ApiUrl == apiPath {
			return true
		}
	}
	return false
}

var apiUserUrlList []TApiUserUrl

func LoadAllApiUserUrl() (err error) {

	apiUserUrlList, _, err = GetAllTApiUserUrl(nil, nil, nil, nil, 0, 10000, false)
	for key, _ := range allApiUserUrlMap {
		delete(allApiUserUrlMap, key)
	}
	for _, apiuserurl := range apiUserUrlList {
		if apiuserurl.Enable == 1 {
			allApiUserUrlMap[apiuserurl.ApiUrl] = append(allApiUserUrlMap[apiuserurl.ApiUrl], apiuserurl.UserToken)
		}
	}
	return
}

//key 是api url 的id ,value是有权限访问该url的用户token列表
var allApiUserUrlMap map[string][]string = make(map[string][]string)

func GetUserListByApiUrl(apiUrl string) []string {
	return allApiUserUrlMap[apiUrl]
}
func GetAllApiUserUrlList() map[string][]string {
	return allApiUserUrlMap
}
func BatchInsertAPIUserUrl(apiUserUrlList []*TApiUserUrl) (err error) {
	if len(apiUserUrlList) <= 0 {
		return nil
	}
	o := orm.NewOrm()
	insertStr := "insert ignore into " + new(TApiUserUrl).TableName() + "(api_url,enable,user_token) values "
	for i, item := range apiUserUrlList {
		insertStr += ("('" + item.ApiUrl + "'," + strconv.Itoa(int(item.Enable)) + ",'" + item.UserToken + "')")
		if i < (len(apiUserUrlList) - 1) {
			insertStr += ","
		}
	}
	insertStr += ";"
	_, err = o.Raw(insertStr).Exec()
	return
}
func BatchRemoveAPIUserUrl(api_url string, apiUserUrlList []*TApiUserUrl) (err error) {
	if len(apiUserUrlList) <= 0 {
		return nil
	}
	o := orm.NewOrm()
	qs := o.QueryTable(new(TApiUserUrl))
	var deleteusers []string
	for _, item := range apiUserUrlList {
		deleteusers = append(deleteusers, item.UserToken)
	}
	_, err = qs.Filter("user_token__in", deleteusers).Filter("api_url", api_url).Delete()
	return
}
func BatchRemoveAPIUserUrlByUser(usertoken string, apiUserUrlList []*TApiUserUrl) (err error) {
	if len(apiUserUrlList) <= 0 {
		return nil
	}
	o := orm.NewOrm()
	qs := o.QueryTable(new(TApiUserUrl))
	var deleteurls []string
	for _, item := range apiUserUrlList {
		deleteurls = append(deleteurls, item.ApiUrl)
	}
	_, err = qs.Filter("user_token", usertoken).Filter("api_url__in", deleteurls).Delete()
	return
}
